package com.seari.movedata.utils;

import com.seari.movedata.bean.CacheInfo;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class LocalCacheUtils {

    //默认的缓存容量
    private static int DEFAULT_CAPACITY = 10;
    //最大容量
    private static int MAX_CAPACITY = 100;
    //刷新缓存的频率
    private static int MONITOR_DURATION = 2;
//   启动监控线程
//    static {
//        new Thread(new TimeoutTimerThread()).start();
//    }
    //使用默认容量创建一个Map
    private static ConcurrentHashMap<String, CacheInfo> cache = new ConcurrentHashMap<String, CacheInfo>(
            DEFAULT_CAPACITY);

    /**
     * 将key-value 保存到本地缓存并制定该缓存的过期时间
     *
     * @param key
     * @param value
     * @param expireTime 过期时间，如果是-1 则表示永不过期
     * @return
     */
    public boolean putValue(String key, Object value, int expireTime) {
        return putCloneValue(key, value, expireTime);
    }

    /**
     * 将值通过序列化clone 处理后保存到缓存中，可以解决值引用的问题
     *
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    private boolean putCloneValue(String key, Object value, int expireTime) {
        try {
            if (cache.size() >= MAX_CAPACITY) {
                return false;
            }
            // 序列化赋值
            CacheInfo entityClone = clone(new CacheInfo(value, System.nanoTime(), expireTime));
            cache.put(key, entityClone);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     * 序列化 克隆处理
     * @param object
     * @return
     */
    private <T extends Serializable> T clone(T object) {
        T cloneObject = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            oos.close();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            cloneObject = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObject;
    }

    /**
     *从本地缓存中获取key对应的值，如果该值不存则则返回null
     *
     * @param key
     * @return
     */
    public Object getValue(String key) {
        return cache.get(key).getValue();
    }

    /**
     * 清空所有
     */
    public void clear() {
        cache.clear();
    }

    /**
     * 过期处理线程
     */
    static class TimeoutTimerThread implements Runnable {
        public void run() {
            while (true) {
                try {
                    System.out.println("Cache monitor");
                    TimeUnit.SECONDS.sleep(MONITOR_DURATION);
                    checkTime();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 过期缓存的具体处理方法
         * @throws Exception
         */
        private void checkTime() throws Exception {
            //"开始处理过期 ";
            for (String key : cache.keySet()) {
                CacheInfo tce = cache.get(key);
                long timoutTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime()
                        - tce.getGmtModify());
                //" 过期时间 : "+timoutTime);
                if (tce.getExpire() > timoutTime) {
                    continue;
                }
                System.out.println(" 清除过期缓存 ： " + key);
                //清除过期缓存和删除对应的缓存队列
                cache.remove(key);
            }
        }
    }
    public void initLocalCache(List<String> aiKeyList, List<String> diKeyList){

        Jedis jedis = JedisPoolUtils.getJedis();

        LocalCacheUtils localCacheUtils = new LocalCacheUtils();
        if (!CommonUtils.objectIsNull(aiKeyList)) {
            Pipeline pipeline = jedis.pipelined();
            for (int i = 0; i < aiKeyList.size(); i++) {
                pipeline.hgetAll(aiKeyList.get(i));
            }
            List<Object> aiResults = pipeline.syncAndReturnAll();
            for(int i = 0; i < aiKeyList.size(); i++){
                String keyStr = aiKeyList.get(i);
                Object valueStr = aiResults.get(i);
                localCacheUtils.putValue(keyStr,valueStr,-1);
            }
        }

        if (!CommonUtils.objectIsNull(aiKeyList)) {
            Pipeline pipeline = jedis.pipelined();
            for (int j = 0; j < diKeyList.size(); j++) {
                pipeline.hgetAll(diKeyList.get(j));
            }
            List<Object> diResults = pipeline.syncAndReturnAll();
            for(int j = 0; j < diKeyList.size(); j++){
                String keyStr = diKeyList.get(j);
                Object valueStr = diResults.get(j);
                localCacheUtils.putValue(keyStr,valueStr,-1);
            }
        }
    }

    public static void main(String args[]){
        LocalCacheUtils localCacheUtils = new LocalCacheUtils();
    List<String> aiKeyList = new ArrayList<String>();
    aiKeyList.add("simulation_AI");
    aiKeyList.add("AI");

    List<String> diKeyList = new ArrayList<String>();
    diKeyList.add("simulation_DI");
    diKeyList.add("DI");

//        localCacheUtils.putCloneValue("aaa","bbb",-1);
//        LocalCacheUtils localCacheUtils9999 = new LocalCacheUtils();
//        localCacheUtils.putCloneValue("ccc","ddd",-1);
//        System.out.println(localCacheUtils.getValue("aaa"));
//        System.out.println(localCacheUtils.getValue("ccc"));
   localCacheUtils.initLocalCache(aiKeyList,diKeyList);
        System.out.println((Map<String, Object>)localCacheUtils.getValue("simulation_AI"));
        System.out.println((Map<String, Object>)localCacheUtils.getValue("simulation_DI"));
        System.out.println((Map<String, Object>)localCacheUtils.getValue("AI"));
        System.out.println((Map<String, Object>)localCacheUtils.getValue("DI"));
    }
}
